﻿using Nova_BLL;
using Nova_Common;
using Nova_Common.Extend;
using Nova_DAL;
using Nova_MOD;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Manage_SearchTrayInfo : System.Web.UI.Page
{
    Nova_DAL.DbHelper dbHelper = new DbHelper();

    TCommandsDetailBll CmdDetialBll = new TCommandsDetailBll();

    string[] ExtensionLanelists = new string[] { "01" };
    string addStorageList_Pid = string.Empty;
    string MatCode = string.Empty;
    string SecMatId = string.Empty;
    string Num = string.Empty;
    string GroupType = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            addStorageList_Pid = Request["pid"] != null ? Request["pid"].ToString() : string.Empty;
            MatCode = Request["matCode"] != null ? Request["matCode"].ToString() : string.Empty;
            SecMatId = Request["secMatId"] != null ? Request["SecMatId"].ToString() : "0";
            Num = Request["num"] != null ? Request["num"].ToString() : "0";
            GroupType = Request["groupType"].ToString();
        }
        catch (Exception)
        { }

        if (!IsPostBack)
        {
            gvBind();
        }
    }

    private void gvBind()
    {
        if (!IsPostBack)
        {
            DataTable dt1 = GetDataSet();
            DataTable dt2 = GetDataSet2();
            DataTable dt = TableList.DataTableUnion(dt1,dt2,"newtable");
            gv.DataSource = dt;
            gv.DataBind();
        }
    }

    private DataTable GetDataSet()
    {
        string sqlStr = @"SELECT TRP.Tray_ID,TRP.Pos_ID, TBM.Mat_Code,TBM.Mat_Name,TBM.S02,TBM.TM03,TBS.Mat_Num,ISNULL(TCD.Tray_ID,'') CmdTrayId,
                    TBM.S01,TBM.TM01,TBS.CDT FROM dbo.TBase_Storage TBS INNER JOIN
                    (SELECT ContainerID,COUNT(ContainerID) AllMaterialCount FROM dbo.TBase_Storage WHERE ContainerID
                    IN (SELECT ContainerID FROM dbo.TBase_Storage WHERE Sec_Mat_ID=@Sec_Mat_ID)
                    GROUP BY ContainerID) TBST ON TBS.ContainerID = TBST.ContainerID
                    INNER JOIN dbo.TRel_TrayPosContainer TRT 
                    ON TRT.ContainerID = TBS.ContainerID INNER JOIN dbo.TBase_TrayPos TBT 
                    ON TRT.Relations_ID = TBT.Relations_ID INNER JOIN dbo.TRelations TRP
                    ON TBT.Tray_ID = TRP.Tray_ID  INNER JOIN dbo.TBase_Position TBP
                    ON TRP.Pos_ID = TBP.Pos_ID INNER JOIN dbo.TBase_Interface TBI
                    ON TBS.Sec_Mat_ID = TBI.Sec_Mat_ID INNER JOIN dbo.TBase_Material TBM
                    ON TBI.Mat_Code = TBM.Mat_Code  LEFT JOIN dbo.TCommands TCD
					ON TRP.Tray_ID = TCD.Tray_ID
                    WHERE TBS.Sec_Mat_ID =@Sec_Mat_ID AND TRP.Pos_ID <>'200000000000' AND TBP.Pos_State <> 0 
                    AND TBM.GroupType = @GroupType ORDER BY TBST.AllMaterialCount ASC ,TBS.CDT ASC";
        DbCommand cmd = dbHelper.GetSqlStringCommond(sqlStr);
        dbHelper.AddInParameter(cmd, "@Sec_Mat_ID", DbType.Int64, SecMatId);
        dbHelper.AddInParameter(cmd, "@GroupType", DbType.String, GroupType);
        DataTable dt = dbHelper.ExecuteDataTable(cmd);
        return dt;
    }

    private DataTable GetDataSet2()
    {
        string sqlStr = @"SELECT TRP.Tray_ID,TRP.Pos_ID ,TBM.Mat_Code,TBM.Mat_Name,TBM.S02,TBM.TM03,TBS.Mat_Num, ISNULL(TCD.Tray_ID,'') CmdTrayId,
                    TBM.S01,TBM.TM01, TBS.CDT FROM dbo.TBase_Storage TBS INNER JOIN
                    (SELECT TOP (8)  TBS.ContainerID,COUNT(TBS.ContainerID) AllMaterialCount FROM dbo.TBase_Storage  TBS
                    INNER JOIN dbo.TBase_Interface TBI ON TBS.Sec_Mat_ID = TBI.Sec_Mat_ID
                    INNER JOIN dbo.TBase_Material TBM ON TBI.Mat_Code =TBM.Mat_Code
                    WHERE TBS.ContainerID NOT IN (SELECT ContainerID FROM dbo.TBase_Storage WHERE Sec_Mat_ID = @Sec_Mat_ID)
                    GROUP BY TBS.ContainerID ORDER BY AllMaterialCount) TBST 
                    ON TBS.ContainerID = TBST.ContainerID
                    INNER JOIN dbo.TRel_TrayPosContainer TRT 
                    ON TRT.ContainerID = TBS.ContainerID INNER JOIN dbo.TBase_TrayPos TBT 
                    ON TRT.Relations_ID = TBT.Relations_ID INNER JOIN dbo.TRelations TRP
                    ON TBT.Tray_ID = TRP.Tray_ID  INNER JOIN dbo.TBase_Position TBP
                    ON TRP.Pos_ID = TBP.Pos_ID INNER JOIN dbo.TBase_Interface TBI
                    ON TBS.Sec_Mat_ID = TBI.Sec_Mat_ID INNER JOIN dbo.TBase_Material TBM
                    ON TBI.Mat_Code = TBM.Mat_Code  LEFT JOIN dbo.TCommands TCD
					ON TRP.Tray_ID = TCD.Tray_ID
                    WHERE TRP.Pos_ID <>'200000000000'  AND TBP.Pos_State <> 0   AND TBM.GroupType = @GroupType
                    ORDER BY TBST.AllMaterialCount,TBS.CDT ASC";
        DbCommand cmd = dbHelper.GetSqlStringCommond(sqlStr);
        dbHelper.AddInParameter(cmd, "@Sec_Mat_ID", DbType.Int64, SecMatId);
        dbHelper.AddInParameter(cmd, "@GroupType", DbType.String, GroupType);
        DataTable dt = dbHelper.ExecuteDataTable(cmd);
        dt = dt.Rows.Count > 0 ? GetGvTable(dt) : dt;
        return dt;
    }

    private DataTable GetGvTable(DataTable dt)
    {
        List<ReplenTrayInfoModel> newList = new List<ReplenTrayInfoModel>();
        List<ReplenTrayInfoModel> list = TableList.DataTableToList<ReplenTrayInfoModel>(dt);
        foreach (var model in list)
        {
            if (newList.Exists(x => x.Tray_ID == model.Tray_ID))
            {
                ReplenTrayInfoModel storageModel = newList.Find(x => x.Tray_ID == model.Tray_ID);
                storageModel.Mat_Name = string.Format("{0},{1}", storageModel.Mat_Name, model.Mat_Name);
                storageModel.Mat_Num = storageModel.Mat_Num + model.Mat_Num;
                storageModel.S01 = "非当前物料";
                storageModel.TM01 = "非当前物料";
                storageModel.S02 = string.Empty;
                storageModel.TM03 = string.Empty;
                // storageModel.MAT_NAME + "/" + model.MAT_NAME;
            }
            else
            {
                model.Mat_Name = string.Format("{0}", model.Mat_Name);
                model.S01 = "非当前物料";
                model.TM01 = "非当前物料";
                model.S02 = string.Empty;
                model.TM03 = string.Empty;
                newList.Add(model);
            }
        }

        return TableList.ListToDataTable(newList);
    }

    protected void ibtnQuery_Click(object sender, ImageClickEventArgs e)
    {
        int chkSelectIndex = -1;
        for (int i = 0; i < gv.Rows.Count; i++)
        {
            CheckBox chkSelect = (CheckBox)gv.Rows[i].Cells[0].FindControl("chkSelect");
            if (chkSelect.Checked)
            {
                chkSelectIndex = i;
            }
        }
        if (chkSelectIndex < 0)
        {
            ShowBox.MessageBox(this.Page, "请选择勾选需要补货的托盘!");
        }
        else
        {
            LinkButton labTray_ID = (LinkButton)this.gv.Rows[chkSelectIndex].FindControl("labTray_ID");
            Label labPos_ID = (Label)this.gv.Rows[chkSelectIndex].FindControl("labPos_ID");
            Label labMat_Code = (Label)this.gv.Rows[chkSelectIndex].FindControl("labMat_Code");
            Label labMat_Name = (Label)this.gv.Rows[chkSelectIndex].FindControl("labMat_Name");
            Label labNum = (Label)this.gv.Rows[chkSelectIndex].FindControl("lblMat_Num");
            Label lblCmdTrayId = (Label)this.gv.Rows[chkSelectIndex].FindControl("lblCmdTrayId");
            if (!lblCmdTrayId.Text.IsEmpty())
            {
                ShowBox.MessageBox(this.Page, "此托盘已经生成指令，需等指令完成后才能再次选择此托盘!");
                return;
            }

            #region 
            //双伸位巷道 后面的货位（偶数层）添加能否出库的业务逻辑判断，不满足条件提示
            //if ((Convert.ToInt32(labPos_ID.Text.Substring(8, 2)) % 2) == 0 && ExtensionLanelists.Contains(labPos_ID.Text.Substring(2, 2)))// 双伸位 后面的货位
            //{
            //    long Pos_ID_Front = (Convert.ToInt64(labPos_ID.Text.Substring(0, 10)) - 1) * 100;
            //    string sqlStr = string.Format(@"select * from  TBase_Position where Pos_ID={0}", Pos_ID_Front);
            //    var cmd = dbHelper.GetSqlStringCommond(sqlStr);
            //    var ds = dbHelper.ExecuteDataSet(cmd);
            //    if (ds.Tables[0].Rows.Count > 0)
            //    {
            //        if (Convert.ToInt16(ds.Tables[0].Rows[0]["Pos_State"]) == 2)
            //        {
            //            ShowBox.MessageBox(this.Page, string.Format("{0}前面的货位有入库预定，此货位的货物不能出库!", labPos_ID.Text));
            //            return;
            //        }

            //        if (Convert.ToInt16(ds.Tables[0].Rows[0]["Pos_State"]) == 6)
            //        {
            //            ShowBox.MessageBox(this.Page, string.Format("{0}前面的货位有移库预定，此货位的货物不能出库!", labPos_ID.Text));
            //            return;
            //        }

            //    }
            //}

            #endregion

            string val = labMat_Code.Text + "|" + labMat_Name.Text + "|" + labNum.Text + "|" + addStorageList_Pid + "|" + labTray_ID.Text + "|" + labPos_ID.Text;
            if (!val.IsEmpty())
            {
                // this.Page.ClientScript.RegisterStartupScript(typeof(string), "Nova", "window.returnValue='" + val + "';top.close();", true);
                this.Page.ClientScript.RegisterStartupScript(typeof(string), "Nova1", "window.opener.document.getElementById('hidden').value='" + val + "';window.opener.document.getElementById('form1').submit();top.close();", true);
                return;
            }
        }
    }

    protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex != -1)
        {
            Label lblCmdTrayId = (Label)e.Row.FindControl("lblCmdTrayId");
            if (!lblCmdTrayId.Text.IsEmpty())
            {
                e.Row.ForeColor = Color.Red;
            }

            LinkButton button = (LinkButton)e.Row.FindControl("labTray_ID");
            // button.Attributes["onclick"] = string.Format("window.showModalDialog('/Views/MetarPOP.aspx?PosID={0}', window, 'dialogWidth=710px;dialogHeight=450px;scroll:no;resizable:no;status:0;menubar=no,scrollbars=yes,resizable=yes,fullscreen=0');", button.CommandArgument.ToString());

            string str = string.Format("javascript:window.open('../Views/MetarPOP.aspx?&PosID={0}', 'newwindow', 'Height=450px,Width=1100px,top=200, left=300, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no');document.URL=location.href;void(0);",
                     button.CommandArgument.ToString());
            button.Attributes.Add("onclick", str);
        }
    }

    protected void ibtnSearch_Click(object sender, ImageClickEventArgs e)
    {
        string sqlStr = @"Select TBP.Pos_ID, TRP.Tray_ID,TBM.Mat_Code,TBM.Mat_Name, TBS.Mat_Num,TBI.TS01,
                        TBM.S05,TBM.S01,ISNULL(TCD.Tray_ID,'') CmdTrayId,TBS.CDT
                        From TBase_Storage TBS LEFT JOIN TRel_TrayPosContainer 
                        TRT ON TBS.ContainerID=TRT.ContainerID LEFT JOIN TBase_TrayPos TBT 
                        ON TBT.Relations_ID = TRT.Relations_ID LEFT JOIN TRelations TRP ON 
                        TRP.Tray_ID = TBT.Tray_ID LEFT JOIN TBase_Position TBP ON TRP.Pos_ID = TBP.Pos_ID 
                        LEFT JOIN TBase_InterFace TBI ON TBI.Sec_Mat_ID =TBS.Sec_Mat_ID 
						LEFT JOIN TBase_Material TBM ON TBM.Mat_Code = TBI.Mat_Code
	                    LEFT JOIN dbo.TCommands TCD ON TRP.Tray_ID = TCD.Tray_ID
                        WHERE TRP.Pos_ID <> '200000000000' ";
        if (string.IsNullOrWhiteSpace(txtTray_ID.Text) && string.IsNullOrWhiteSpace(txtMat_Name.Text))
        {
            ShowBox.MessageBox(this.Page, "请填写托盘号或者物料名称!");
            return;
        }
        else
        {
            if (!string.IsNullOrWhiteSpace(txtTray_ID.Text))
            {
                sqlStr += " AND TRP.Tray_ID like '%" + txtTray_ID.Text.ToString() + "%'";
            }
            if (!string.IsNullOrWhiteSpace(txtMat_Name.Text))
            {
                sqlStr += " AND TBM.Mat_Name LIKE '%" + txtMat_Name.Text.ToString() + "%'";
            }
            DbCommand cmd = dbHelper.GetSqlStringCommond(sqlStr);
            DataTable dt = dbHelper.ExecuteDataTable(cmd);
            dt = dt.Rows.Count > 0 ? GetGvTable(dt) : dt;
            gv.DataSource = dt;
            gv.DataBind();
        }

    }
}